package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.app.domain.ExternalResponse;
import com.app.domain.HnsbDataResult;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.wl.WlResult;
import com.app.domain.wl.WlYjData;
import com.app.service.HnsbService;
import com.app.service.UploadParameterService;
import com.app.service.UploadService;
import com.app.service.YjDataService;
import com.app.utils.MD5Utils;
import com.app.utils.TimeHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/hnsb")
public class HnsbController {
    @Value("${yj.hnsb.serverHost}")
    private String serverHost;
    @Value("${yj.hnsb.platformdeviceid}")
    private String platformdeviceid;
    @Value("${yj.hnsb.vendorno}")
    private String vendorno;
    @Value("${yj.hnsb.deviceno}")
    private String deviceno;
    @Value("${yj.hnsb.userkey}")
    private String userkey;
    @Value("${yj.hnsb.secret}")
    private String secret;
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadService uploadService;
    @Autowired
    HnsbService hnsbService;

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException {
        ExternalResponse externalResponse = null;
        int total = ids.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuffer responseContent = new StringBuffer();
        responseContent.append("本次共上传数据：【" + total + "】条,");
        List<YjData> yjDataList = yjDataService.findList(ids);
        List<List<YjData>> groupList = new ArrayList<>();
        yjDataList.stream().collect(Collectors.groupingBy(YjData::getBridge_code, Collectors.toList())).forEach((bridge_code, yjDataGroupList) -> {
            groupList.add(yjDataGroupList);
        });
        UploadParameter uploadParameter = uploadParameterService.findOne("34");
        for (List<YjData> yjData : groupList) {
            List<Integer> userIds = yjData.stream().map(o -> o.getId()).collect(Collectors.toList());
            List<WlYjData> wlYjDataList = hnsbService.getWlYjData(yjData, uploadParameter, vendorno, deviceno, platformdeviceid);
            int count = 0;
            for (WlYjData wlYjData : wlYjDataList) {
                String s = JSON.toJSONString(wlYjData);
                System.out.printf(s);
                Map<String, String> maps = new HashMap<>();
                String currentCompactTime1 = TimeHelper.getCurrentCompactTime1();
                maps.put("userkey", userkey);
                maps.put("time", currentCompactTime1);
                String md532bit = null;
                try {
                    md532bit = MD5Utils.MD5_32bit(userkey + secret + currentCompactTime1);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                maps.put("sign", md532bit);
                HnsbDataResult hnsbDataResult = hnsbService.sendMessage(serverHost, s, maps);
                if (hnsbDataResult.getSuccess() && hnsbDataResult.getCode() == 200) {
                    count++;
                }
            }
            if (count == wlYjDataList.size()) {
                for (Integer userId : userIds) {
                    updateState("1", String.valueOf(userId));
                    succTotal++;
                }
            } else {
                for (Integer userId : userIds) {
                    updateState("0", String.valueOf(userId));
                    failTotal++;
                }
            }

        }
        responseContent.append("成功【" + succTotal + "】条,失败" + failTotal + "条");
        externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        return externalResponse;
    }


    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}
